package com.iecas.handler;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.iecas.enums.BizEnum;
import com.iecas.enums.ResponseEnum;
import com.iecas.holder.TokenHolder;
import com.iecas.launch.Client;
import com.iecas.launch.Server;
import com.iecas.request.JoinReq;
import com.iecas.request.Root;
import com.iecas.response.BaseResponse;
import com.iecas.response.LoginResp;
import com.iecas.utils.RequestUtils;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class LoginRespHandler extends BaseHandler {

    @Override
    BaseResponse handle(Root baseRequest, Server server, Client client, SocketChannel socketChannel) {
        LoginResp loginResp = (LoginResp) baseRequest;
        StaticLog.info("接收到登录响应: {}", JSONUtil.toJsonStr(loginResp));
        loginResp.setCode(BizEnum.LOGIN_RESP.getCode());
        int code = loginResp.getStatus();
        if (code == ResponseEnum.SUCCESS.getCode()) {
            // 唤出游戏窗口
            String token = loginResp.getToken();
            TokenHolder.set(token);
            client.closeLoginFrame();
            client.showGameFrame();
            client.getGameFrame().startSendHeartBeat();
            // 发送加入请求
            JoinReq joinReq = new JoinReq();
            joinReq.setToken(token);
            joinReq.setCode(BizEnum.JOIN_REQ.getCode());
            ByteBuffer encode = RequestUtils.encode(joinReq);
            client.write(encode);
        } else {
            // 提示错误信息
            String msg = loginResp.getMsg();
            client.getLoginFrame().setErrMsg(msg);
        }
        return null;
    }
}
